import React, { ReactElement, useContext, useEffect, useMemo } from 'react';
import { Animated, Easing, View } from 'react-native';

import { loading } from '../../../../constant/resource';
import { Store } from '../../reducer';
import styles from './style';

export default (): ReactElement => {
  const { state } = useContext(Store);
  const { showLoading } = state;
  const spinValue: Animated.Value = new Animated.Value(0);

  useEffect((): (() => void) => {
    const timer = Animated.loop(
      Animated.timing(spinValue, {
        toValue: 1, // 最终值 为1，这里表示最大旋转 360度
        duration: 1500,
        easing: Easing.linear,
        useNativeDriver: true
      })
    );
    if (showLoading) {
      timer.start();
    }
    return (): void => {
      if (timer) {
        timer.stop();
      }
    };
  }, [showLoading, spinValue]);

  const spinRotate = spinValue.interpolate({
    inputRange: [0, 1], // 输入值
    outputRange: ['0deg', '-360deg'] // 输出值
  });

  return useMemo((): ReactElement => {
    if (showLoading) {
      return (
        <View style={styles.container}>
          <View style={styles.content}>
            <Animated.Image
              source={loading}
              style={[styles.loading, { transform: [{ rotate: spinRotate }] }]}
            />
          </View>
        </View>
      );
    }
    return <View />;
  }, [showLoading, spinRotate]);
};
